package com.johnny.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

import com.johnny.data.Info;

public class SerializableUtil {
	private static SerializableUtil instance = new SerializableUtil();
	private ObjectOutputStream obos;
	private ObjectInputStream ois;

	public static SerializableUtil getInstance() {
		return instance;
	}
	
	private SerializableUtil(){}

	public void putInfo(Info info) throws IOException {
		File dir = new File("data/" + info.getClass().getSimpleName());
		if (!dir.exists())
			dir.mkdirs();
		File file = new File("data/" + info.getClass().getSimpleName() + "/"
				+ info.getFileName());
		if (file.exists()) {
			file.delete();
		}
		file.createNewFile();
		FileOutputStream fos = new FileOutputStream(file);
		obos = new ObjectOutputStream(fos);

		obos.writeObject(info);
		obos.close();
	}

	public List getAllInfos(Class clazz) throws Exception {
		List result = new ArrayList<>();
		File dir = new File("data/" + clazz.getSimpleName());
		File[] files = dir.listFiles();
		if (files == null) {
			return result;
		}
		for (int i = 0; i < files.length; i++) {
			FileInputStream fis = new FileInputStream(files[i]);
			ois = new ObjectInputStream(fis);
			result.add(ois.readObject());
			ois.close();
		}
		return result;
	}
}
